/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
// import request from 'utils/fetch'
import lodash from 'lodash';
import { apiProxy } from 'utils/app.conf';
import request, { axios, fetch } from 'utils/request';
import api from './config';

/**
 * @desc 统一调用后台入口
 * @param {key} 方法key在apiConfig配置的
 * @param {params} 请求的参数
 */
const env = process.env.NODE_ENV === 'development';

/**
 * @desc 通过改方法获取后台的请求信息
 * @param {key} 方法methodkey
 */
export function getMethodInfo(key) {
  const currentHandler = api[key];
  if (!currentHandler) {
    console.error(`ServiceHandler Error Not Match MethodKey${key}`);
  }
  let url = currentHandler.url.trim();
  if (apiProxy) {
    url = apiProxy + url;
  }
  return lodash.assign({}, currentHandler, { url, method: currentHandler.method.toUpperCase() });
}

/**
 * @param {key} 方法methodKey
 * @param {params} 参数：json|FormData|obj
 * @param {suffix} Url上的参数
 */
export async function callMethod({ key, params, suffix }) {
  const currentHandler = getMethodInfo(key);
  const { method, mocktable, mockhandler, headers = {}, url } = currentHandler;

  const newOptions = { method, headers };

  if (method === 'GET') {
    newOptions.query = params;
  } else {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type':
        method === 'FORMPOST' || params instanceof FormData
          ? 'application/x-www-form-urlencoded'
          : 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    newOptions.body = params;
  }

  // 针对mock 生成的
  if (env && mocktable) {
    lodash.assign(newOptions.headers, { mocktable, mockhandler });
  }

  try {
    const { success = false, ...other } = await request(suffix ? url + suffix : url, newOptions);
    return { success, ...other };
  } catch (error) {
    console.error(error);
    return { success: false };
  }
}

// 这个用于某些业务自定义的请求 ，比如上传等等
export { axios, fetch };
